package com.mhkj.common.util.office;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.util.PDFMergerUtility;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.mhkj.common.util.Office2PDF;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

public class WordUtil4 {

	// word运行程序对象
	private ActiveXComponent app;
	// 选定的范围或插入点
	private static Dispatch selection;
	private static Dispatch document = null;

	public void openWord(boolean makeVisible) {
		// Open Word if we\'ve not done it already
		if (app == null) {
			app = new ActiveXComponent("Word.Application");
		}
		// Set the visible property as required.
		Dispatch.put(app, "Visible", new Variant(makeVisible));
	}

	/**
	 * 创建Word文档
	 *
	 */
	public void createNewDocument() {
		// Find the Documents collection object maintained by Word
		Dispatch documents = Dispatch.get(app, "Documents").toDispatch();
		// Call the Add method of the Documents collection to create
		// a new document to edit
		document = Dispatch.call(documents, "Add").toDispatch();
	}

	/**
	 * 保存Word文档到指定的目录(包括文件名)
	 * 
	 * @param filePath
	 */
	public void saveWordFile(final String filePath) {
		// 保存文件
		Dispatch.invoke(document, "SaveAs", Dispatch.Method, new Object[] { filePath, new Variant(0) }, new int[1]);
		// 作为word格式保存到目标文件
		Variant f = new Variant(false);
		Dispatch.call(document, "Close", f);
	}

	/**
	 * 汇总文件(Word)
	 * 
	 * @param fileList
	 * @param savepaths
	 */
/*	public void uniteDoc(List<String> fileList, String savepaths) {
		if (fileList.size() == 0 || fileList == null) {
			return;
		}
		// 打开word
		ActiveXComponent app = new ActiveXComponent("Word.Application");// 启动word
		try {
			// 设置word不可见
			app.setProperty("Visible", new Variant(false));
			// 获得documents对象
			Dispatch docs = app.getProperty("Documents").toDispatch();
			// 打开第一个文件
			Dispatch doc = null;
			String[] fileStrs = fileList.get(fileList.size() - 1).toString().split("\\.");
			// 如果是图片，则以图片的方式添加
			if (fileStrs[fileStrs.length - 1].toUpperCase().equals("JPG")
					|| fileStrs[fileStrs.length - 1].toUpperCase().equals("JPEG")
					|| fileStrs[fileStrs.length - 1].toUpperCase().equals("PDF")
					|| fileStrs[fileStrs.length - 1].toUpperCase().equals("PNG")
					|| fileStrs[fileStrs.length - 1].toUpperCase().equals("BMP")) {

				// 如果是pdf文件，则需要先转换为图片
				if (fileStrs[fileStrs.length - 1].toUpperCase().equals("PDF")) {
					this.pdfjpg(fileList.get(fileList.size() - 1).toString(), fileStrs[0] + ".jpg");
					fileList.set(fileList.size() - 1, fileStrs[0] + ".jpg");
				}

				// 创建一个新的Word文档
				String wordFile = fileStrs[0] + ".doc";
				this.createNewWord(wordFile);
				// 将新的文档加载到程序中
				doc = Dispatch
						.invoke((Dispatch) docs, "Open", Dispatch.Method,
								new Object[] { wordFile, new Variant(false), new Variant(true) }, new int[3])
						.toDispatch();
				// 加载图片
				Dispatch.call(Dispatch.get(app.getProperty("Selection").toDispatch(), "InLineShapes").toDispatch(),
						"AddPicture", fileList.get(fileList.size() - 1));

				// document = Dispatch.call(docs,"Add").toDispatch();
				// Dispatch.call(Dispatch.get(app.getProperty("Selection").toDispatch(),
				// "InLineShapes").toDispatch(),"AddPicture", fileList.get(i));
			} else {
				doc = Dispatch.invoke(
						(Dispatch) docs, "Open", Dispatch.Method, new Object[] {
								(String) fileList.get(fileList.size() - 1), new Variant(false), new Variant(true) },
						new int[3]).toDispatch();
			}

			// 到文档末尾
			// Dispatch.call(app.getProperty("Selection").toDispatch(), "EndKey", "6");
			// 插入分页符
			// Dispatch.call(app.getProperty("Selection").toDispatch(), "InsertBreak", new
			// Variant(7));

			// 追加文件
			for (int i = 0; i < fileList.size() - 1; i++) {
				fileStrs = fileList.get(i).toString().split("\\.");

				// 如果是图片，则以图片的方式添加
				if (fileStrs[fileStrs.length - 1].toUpperCase().equals("JPG")
						|| fileStrs[fileStrs.length - 1].toUpperCase().equals("JPEG")
						|| fileStrs[fileStrs.length - 1].toUpperCase().equals("PDF")
						|| fileStrs[fileStrs.length - 1].toUpperCase().equals("PNG")
						|| fileStrs[fileStrs.length - 1].toUpperCase().equals("BMP")) {
					// Dispatch.call(,"AddPicture", fileList.get(i));
					// 如果是pdf文件，则需要先转换为图片
					if (fileStrs[fileStrs.length - 1].toUpperCase().equals("PDF")) {
						this.pdfjpg(fileList.get(i).toString(), fileStrs[0] + ".jpg");
						fileList.set(i, fileStrs[0] + ".jpg");
					}
					// 添加图片
					Dispatch.call(Dispatch.get(app.getProperty("Selection").toDispatch(), "InLineShapes").toDispatch(),
							"AddPicture", fileList.get(i));

				} else {

					Dispatch.invoke(app.getProperty("Selection").toDispatch(), "insertFile", Dispatch.Method,
							new Object[] { (String) fileList.get(i), "", new Variant(false), new Variant(false),
									new Variant(false) },
							new int[3]);
				}

				// 到文档末尾
				// Dispatch.call(app.getProperty("Selection").toDispatch(), "EndKey", "6");
				// 插入分页符
				// Dispatch.call(app.getProperty("Selection").toDispatch(), "InsertBreak", new
				// Variant(7));
			}
			// 保存新的word文件
			Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { savepaths, new Variant(1) }, new int[3]);
			Variant f = new Variant(false);
			Dispatch.call((Dispatch) doc, "Close", f);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("合并word文件出错.原因:" + e);
		} finally {
			app.invoke("Quit", new Variant[] {});
		}
	}*/

	/**
	 * 汇总文件(PDF)
	 * 
	 * @param fileList
	 * @param savepaths
	 */
	public void unitePDF(List<String> fileList, String savepaths) throws Exception {
		if (fileList.size() == 0 || fileList == null) {
			return;
		}

		PDFMergerUtility mergePdf = new PDFMergerUtility();/*
		Office2PDF converter = new Office2PDF();*/

		// 添加PDF文件，且只有PDF才可以被汇总
		for (int i = 0; i < fileList.size(); i++) {
			String[] pathTemps = fileList.get(i).split("\\\\");
			String[] fileTemps = pathTemps[pathTemps.length - 1].split("\\.");
			String path = "";
			for (int p = 0; p < pathTemps.length - 1; p++) {
				path += pathTemps[p] + "\\";
			}
			if (fileTemps[fileTemps.length - 1].toUpperCase().equals("PDF")) {
				mergePdf.addSource(fileList.get(i));
			} else if (fileTemps[fileTemps.length - 1].toUpperCase().equals("DOC")
					|| fileTemps[fileTemps.length - 1].toUpperCase().equals("DOCX")) {
				// Word转换为PDF
				Office2PDF.openOffice2Pdf(fileList.get(i), path + fileTemps[0] + ".PDF");
				mergePdf.addSource(path + fileTemps[0] + ".PDF");
			} else if (fileTemps[fileTemps.length - 1].toUpperCase().equals("JPG")
					|| fileTemps[fileTemps.length - 1].toUpperCase().equals("JPEG")) {
				Office2PDF.openOffice2Pdf(fileList.get(i), path + fileTemps[0] + ".PDF");
				mergePdf.addSource(path + fileTemps[0] + ".PDF");
			} else if (fileTemps[fileTemps.length - 1].toUpperCase().equals("XLS")
					|| fileTemps[fileTemps.length - 1].toUpperCase().equals("XLSX")) {
				Office2PDF.openOffice2Pdf(fileList.get(i), path + fileTemps[0] + ".PDF");
				mergePdf.addSource(path + fileTemps[0] + ".PDF");
			}
		}
		// 汇总生成PDF文件
		mergePdf.setDestinationFileName(savepaths);
		mergePdf.mergeDocuments();

		// 删除那些汇总的文件
		for (String filePath : fileList) {
			new File(filePath).delete();
		}

		System.out.print("done");
	}

	/**
	 * pdf文件转换为jpg文件
	 * 
	 * @param pdfFile
	 * @param jpgFile
	 * @throws IOException
	 */
/*	public void pdfjpg(String pdfFile, String jpgFile) throws IOException {

		// load a pdf from a byte buffer
		File file = new File(pdfFile);
		RandomAccessFile raf = new RandomAccessFile(file, "r");
		FileChannel channel = raf.getChannel();
		ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
		PDFFile pdffile = new PDFFile(buf);

		System.out.println("页数： " + pdffile.getNumPages());
		int with = 0;
		int height = 0;
		for (int i = 1; i <= pdffile.getNumPages(); i++) {
			// draw the first page to an image
			PDFPage page = pdffile.getPage(i);
			with = (int) page.getBBox().getWidth();
			height += (int) page.getBBox().getHeight();
		}
		Rectangle rect = new Rectangle(0, 0, with, height);
		BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
		for (int j = 1; j <= pdffile.getNumPages(); j++) {
			PDFPage page = pdffile.getPage(j);
			Rectangle rect1 = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
			Image img = page.getImage(rect1.width, rect1.height, // width &
					// height
					rect1, // clip rect
					null, // null for the ImageObserver
					true, // fill background with white
					true // block until drawing is done
			);

			tag.getGraphics().drawImage(img, 0, rect1.height * (j - 1), rect1.width, rect1.height, null);
		}
		FileOutputStream out = new FileOutputStream(jpgFile); // 输出到文件流
		//JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		encoder.encode(tag); // JPEG编码
		out.close();

	}*/

	/**
	 * 创建新的文档
	 * 
	 * @param filePath
	 */
	public void createNewWord(String filePath) {
		try {
			// Open Word if we\'ve not done it already
			if (app == null) {
				app = new ActiveXComponent("Word.Application");
			}
			// Set the visible property as required.
			Dispatch.put(app, "Visible", new Variant(false));

			// 创建新的文档Word
			Dispatch documents = Dispatch.get(app, "Documents").toDispatch();
			document = Dispatch.call(documents, "Add").toDispatch();
			Dispatch.invoke(document, "SaveAs", Dispatch.Method, new Object[] { filePath, new Variant(0) }, new int[1]);
			// 作为word格式保存到目标文件
			Variant f = new Variant(false);
			Dispatch.call(document, "Close", f);

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("合并word文件出错.原因:" + e);
		} finally {
			app.invoke("Quit", new Variant[] {});
		}
	}

	/*public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		String file1 = "E:\\web1111\\ab1.doc";
		String file2 = "E:\\web1111\\ab2.jpg";
		String file3 = "E:\\web1111\\ab3.pdf";

		list.add(file1);
		list.add(file2);
		list.add(file3);
		try {
			new WordUtil4().unitePDF(list, "E:\\web1111\\ab8.pdf");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// uniteDoc(list,"E:\\Word\\ab8.docx");
		/*
		  Test_Word test = new Test_Word(); test.openWord(true);
		  test.createNewDocument(); test.saveWordFile("E:\\Word\\new.docx");
		 
	}*/
	
	/* public static void main(String[] args) { Test_Word test = new Test_Word();
	  System.out.println(test.tidyWord("E:\\Word\\ab.doc", "E:\\Word\\ab.doc")); 
	 }*/
	 
}